package sdk.webview.fmc.com.fmcsdk.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.dk.bleNfc.BleManager.BleManager;
import com.dk.bleNfc.BleManager.Scanner;
import com.dk.bleNfc.BleManager.ScannerCallback;
import com.dk.bleNfc.BleNfcDeviceService;
import com.dk.bleNfc.DeviceManager.BleNfcDevice;
import com.dk.bleNfc.DeviceManager.ComByteManager;
import com.dk.bleNfc.DeviceManager.DeviceManager;
import com.dk.bleNfc.DeviceManager.DeviceManagerCallback;
import com.dk.bleNfc.Exception.CardNoResponseException;
import com.dk.bleNfc.Exception.DeviceNoResponseException;
import com.dk.bleNfc.Tool.StringTool;
import com.dk.bleNfc.card.FeliCa;
import com.dk.bleNfc.card.Iso14443bCard;
import com.dk.bleNfc.card.Iso15693Card;
import com.dk.bleNfc.card.Mifare;
import com.dk.bleNfc.card.Ntag21x;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.barcode.camera.CameraManager;
import sdk.webview.fmc.com.fmcsdk.barcode.common.AmbientLightManager;
import sdk.webview.fmc.com.fmcsdk.barcode.common.BeepManager;
import sdk.webview.fmc.com.fmcsdk.barcode.common.FinishListener;
import sdk.webview.fmc.com.fmcsdk.barcode.common.InactivityTimer;
import sdk.webview.fmc.com.fmcsdk.barcode.common.IntentSource;
import sdk.webview.fmc.com.fmcsdk.barcode.decode.CaptureActivityHandler;
import sdk.webview.fmc.com.fmcsdk.barcode.view.ViewfinderView;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.URLEncodeUtils;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.view.BluetoothDialog;

/**
 * This activity opens the camera and does the actual scanning on a background
 * thread. It draws a viewfinder to help the user place the barcode correctly,
 * shows feedback as the image processing is happening, and then overlays the
 * results when a scan is successful.
 * <p>
 * 此Activity所做的事： 1.开启camera，在后台独立线程中完成扫描任务；
 * 2.绘制了一个扫描区（viewfinder）来帮助用户将条码置于其中以准确扫描； 3.扫描成功后会将扫描结果展示在界面上。
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class CaptureActivity extends BaseActivity implements
        SurfaceHolder.Callback, OnClickListener {
    private boolean isBind = false;
    private BleNfcDevice bleNfcDevice;
    private Scanner mScanner;
    BleNfcDeviceService mBleNfcDeviceService;
    private Lock mNearestBleLock = new ReentrantLock();// 锁对象
    private BluetoothDevice mNearestBle = null;
    private int lastRssi = -100;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private static final String TAG = CaptureActivity.class.getSimpleName();

    public static final String SCAN_RESULT = "scan_result";

    private static final int PARSE_BARCODE_FAIL = 300;
    private static final int PARSE_BARCODE_SUC = 200;
    final int ASSET_CODE = 0;
    /**
     * 是否有预览
     */
    private boolean hasSurface;

    /**
     * 活动监控器。如果手机没有连接电源线，那么当相机开启后如果一直处于不被使用状态则该服务会将当前activity关闭。
     * 活动监控器全程监控扫描活跃状态，与CaptureActivity生命周期相同.每一次扫描过后都会重置该监控，即重新倒计时。
     */
    private InactivityTimer inactivityTimer;

    /**
     * 声音震动管理器。如果扫描成功后可以播放一段音频，也可以震动提醒，可以通过配置来决定扫描成功后的行为。
     */
    private BeepManager beepManager;

    /**
     * 闪光灯调节器。自动检测环境光线强弱并决定是否开启闪光灯
     */
    private AmbientLightManager ambientLightManager;

    private CameraManager cameraManager;
    /**
     * 扫描区域
     */
    private ViewfinderView viewfinderView;

    private CaptureActivityHandler handler;

    private Result lastResult;

    private boolean isFlashlightOpen;

    /**
     * 【辅助解码的参数(用作MultiFormatReader的参数)】 编码类型，该参数告诉扫描器采用何种编码方式解码，即EAN-13，QR
     * Code等等 对应于DecodeHintType.POSSIBLE_FORMATS类型
     * 参考DecodeThread构造函数中如下代码：hints.put(DecodeHintType.POSSIBLE_FORMATS,
     * decodeFormats);
     */
    private Collection<BarcodeFormat> decodeFormats;

    /**
     * 【辅助解码的参数(用作MultiFormatReader的参数)】 该参数最终会传入MultiFormatReader，
     * 上面的decodeFormats和characterSet最终会先加入到decodeHints中 最终被设置到MultiFormatReader中
     * 参考DecodeHandler构造器中如下代码：multiFormatReader.setHints(hints);
     */
    private Map<DecodeHintType, ?> decodeHints;

    /**
     * 【辅助解码的参数(用作MultiFormatReader的参数)】 字符集，告诉扫描器该以何种字符集进行解码
     * 对应于DecodeHintType.CHARACTER_SET类型
     * 参考DecodeThread构造器如下代码：hints.put(DecodeHintType.CHARACTER_SET,
     * characterSet);
     */
    private String characterSet;

    private Result savedResultToShow;

    private IntentSource source;
    private BluetoothDialog bluetoothDialog;


    private boolean CheckType;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CheckType=getIntent().getBooleanExtra("CheckType",false);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        ambientLightManager = new AmbientLightManager(this);
        LinearLayout ll = (LinearLayout) findViewById(R.id.reportreson_ll);
//		if(getIntent().getBooleanExtra("isshow", false)){  //是否显示遇到扫码问题的栏位
        ll.setVisibility(View.VISIBLE);
//		}else {
//			ll.setVisibility(View.GONE);
//		}
        TextView search_tv = (TextView) findViewById(R.id.search_asset);
        //保持与扫描框宽度一致
        LayoutParams params = (LayoutParams) search_tv.getLayoutParams();
        params.width = getBestWidth(this);
        search_tv.setLayoutParams(params);
        findViewById(R.id.capture_flash).setOnClickListener(this);
        findViewById(R.id.capture_back).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
//				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            }
        });
        findViewById(R.id.reporttreson_tv).setOnClickListener(this);    //跳过
        TextView bluetooth_tv = (TextView) findViewById(R.id.bluetooth_tv);
        String bletooth = getIntent().getStringExtra("bletooth");
        if (bletooth.equals("1")) {
            bluetooth_tv.setVisibility(View.VISIBLE);
        } else {
            bluetooth_tv.setVisibility(View.GONE);
        }
        findViewById(R.id.bluetooth_tv).setOnClickListener(this);    //跳过
        if (getIntent().getBooleanExtra("showSearch", false)) {
            search_tv.setVisibility(View.VISIBLE);

        } else {
            search_tv.setVisibility(View.GONE);
        }

        if(CheckType){
            Intent intent = new Intent(context, H5ForNfcActivity.class);
            intent.putExtra(Constant.SCAN_TO_OPEN_NFC, true);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.capture;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBleNfcDeviceService != null) {
            mBleNfcDeviceService.setScannerCallback(scannerCallback);
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
        }
        // CameraManager must be initialized here, not in onCreate(). This is
        // necessary because we don't
        // want to open the camera driver and measure the screen size if we're
        // going to show the help on
        // first launch. That led to bugs where the scanning rectangle was the
        // wrong size and partially
        // off screen.

        // 相机初始化的动作需要开启相机并测量屏幕大小，这些操作
        // 不建议放到onCreate中，因为如果在onCreate中加上首次启动展示帮助信息的代码的 话，
        // 会导致扫描窗口的尺寸计算有误的bug
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);

        handler = null;
        lastResult = null;

        // 摄像头预览功能必须借助SurfaceView，因此也需要在一开始对其进行初始化
        // 如果需要了解SurfaceView的原理
        // 参考:http://blog.csdn.net/luoshengyang/article/details/8661317
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); // 预览
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            // The activity was paused but not stopped, so the surface still
            // exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(surfaceHolder);

        } else {
            // 防止sdk8的设备初始化预览异常
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

            // Install the callback and wait for surfaceCreated() to init the
            // camera.
            surfaceHolder.addCallback(this);
        }

        // 加载声音配置，其实在BeemManager的构造器中也会调用该方法，即在onCreate的时候会调用一次
        beepManager.updatePrefs();

        // 启动闪光灯调节器
        ambientLightManager.start(cameraManager);

        // 恢复活动监控器
        inactivityTimer.onResume();

        source = IntentSource.NONE;
        decodeFormats = null;
        characterSet = null;
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        ambientLightManager.stop();
        beepManager.close();

        // 关闭摄像头
        cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
        if (isBind) {
            unbindService(mServiceConnection);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if ((source == IntentSource.NONE) && lastResult != null) { // 重新进行扫描
                    restartPreviewAfterDelay(0L);
                    return true;
                }

                break;
            case KeyEvent.KEYCODE_FOCUS:
            case KeyEvent.KEYCODE_CAMERA:
                // Handle these events so they don't launch the Camera app
                return true;

            case KeyEvent.KEYCODE_VOLUME_UP:
                cameraManager.zoomIn();
                return true;

            case KeyEvent.KEYCODE_VOLUME_DOWN:
                cameraManager.zoomOut();
                return true;


        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG,
                    "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        /*hasSurface = false;*/
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult   The contents of the barcode.
     * @param scaleFactor amount by which thumbnail was scaled
     * @param barcode     A greyscale bitmap of the camera data which was decoded.
     */
    public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {

        // 重新计时
        inactivityTimer.onActivity();

        lastResult = rawResult;

        // 把图片画到扫描框
//		viewfinderView.drawResultBitmap(barcode);

        beepManager.playBeepSoundAndVibrate();

//		Toast.makeText(this,
//				"识别结果:" + ResultParser.parseResult(rawResult).toString(),
//				Toast.LENGTH_SHORT).show();

//		Intent intent = new Intent(this, ResultActivity.class);
//		intent.putExtra("result", rawResult.getText());
//		startActivity(intent);
        String result = rawResult.getText().trim();
        XLog.i(result + "扫码");
        if (result.contains("id=") && result.contains("ver=")) {
            result = URLEncodeUtils.decoder(result.substring(result.indexOf("id=") + 3, result.lastIndexOf("&ver=")));
        }
        Intent intent = new Intent();
        intent.putExtra(SCAN_RESULT, result);
        setResult(RESULT_OK, intent);
        finish();
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
        lastResult = null;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }

        if (cameraManager.isOpen()) {
            Log.w(TAG,
                    "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        decodeHints, characterSet, cameraManager);
            }
            decodeOrStoreSavedBitmap(null, null);
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
//			FMCLog.getInstance(CaptureActivity.this).warn("CaptureActivity",ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
//			FMCLog.getInstance(CaptureActivity.this).warn("CaptureActivity",e);
            displayFrameworkBugMessageAndExit();
        }
    }

    /**
     * 向CaptureActivityHandler中发送消息，并展示扫描到的图像
     *
     * @param bitmap
     * @param result
     */
    private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
        // Bitmap isn't used yet -- will be used soon
        if (handler == null) {
            savedResultToShow = result;
        } else {
            if (result != null) {
                savedResultToShow = result;
            }
            if (savedResultToShow != null) {
                Message message = Message.obtain(handler,
                        R.id.decode_succeeded, savedResultToShow);
                handler.sendMessage(message);
            }
            savedResultToShow = null;
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage(getString(R.string.msg_camera_framework_bug));
        builder.setPositiveButton(android.R.string.ok, new FinishListener(this));
        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.capture_flash) {
            if (isFlashlightOpen) {
                cameraManager.setTorch(false); // 关闭闪光灯
                isFlashlightOpen = false;
            } else {
                cameraManager.setTorch(true); // 打开闪光灯
                isFlashlightOpen = true;
            }
        } else if (v.getId() == R.id.reporttreson_tv) {
            Intent intent = new Intent(context, H5ForNfcActivity.class);
            intent.putExtra(Constant.SCAN_TO_OPEN_NFC, true);
            startActivity(intent);
            finish();

        } else if (v.getId() == R.id.bluetooth_tv) {
            //连接蓝牙读卡器
//			//ble_nfc服务初始化
            Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
            isBind = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
            bluetoothDialog = new BluetoothDialog(this, getResources().getString(R.string.search_device));
            bluetoothDialog.setCancelable(false);
            bluetoothDialog.show();
            bluetoothDialog.setClicklistener(new BluetoothDialog.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    bluetoothDialog.dismiss();
                    finish();
                }
            });
        }
    }

    /**
     * 获取扫码区域宽度
     *
     * @param context
     * @return
     */
    public int getBestWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int dim = 5 * screenWidth / 8; // Target 5/8 of each dimension
        if (dim < 240) {
            return 240;
        }
        if (dim > 1200) {
            return 1200;
        }
        return dim;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ASSET_CODE) {
                Log.e("shuchang", "扫码出来的数据------>" + new Gson().toJson(data));
                String assetno = data.getStringExtra("assetno");
                Intent intent = new Intent();
                intent.putExtra(SCAN_RESULT, assetno);
                //是否在手动选择设备界面进行了扫码
                intent.putExtra("isscan", data.getBooleanExtra("isscan", false));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    }


    /*******************************************************************蓝牙部分*********************************************************/
    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            BleNfcDeviceService mBleNfcDeviceService = ((BleNfcDeviceService.LocalBinder) service).getService();
            bleNfcDevice = mBleNfcDeviceService.bleNfcDevice;
            mScanner = mBleNfcDeviceService.scanner;
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
            mBleNfcDeviceService.setScannerCallback(scannerCallback);
            //XLog.i("11111111");
            //开始搜索设备
            searchNearestBleDevice();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBleNfcDeviceService = null;
        }
    };


    //设备操作类回调
    private DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onReceiveConnectBtDevice(boolean blnIsConnectSuc) {
            super.onReceiveConnectBtDevice(blnIsConnectSuc);
            if (blnIsConnectSuc) {
                Message message = blueHandler.obtainMessage(5);
                message.obj = getResources().getString(R.string.device_connect_success);
                message.sendToTarget();
                //连接上后延时500ms后再开始发指令
                try {
                    Thread.sleep(500L);
                    blueHandler.sendEmptyMessage(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onReceiveDisConnectDevice(boolean blnIsDisConnectDevice) {
            super.onReceiveDisConnectDevice(blnIsDisConnectDevice);
            Message message = blueHandler.obtainMessage(5);
            message.obj = getResources().getString(R.string.device_disconnected);
            message.sendToTarget();
            blueHandler.sendEmptyMessage(0);
        }

        @Override
        public void onReceiveConnectionStatus(boolean blnIsConnection) {
            super.onReceiveConnectionStatus(blnIsConnection);
        }

        @Override
        public void onReceiveInitCiphy(boolean blnIsInitSuc) {
            super.onReceiveInitCiphy(blnIsInitSuc);
        }

        @Override
        public void onReceiveDeviceAuth(byte[] authData) {
            super.onReceiveDeviceAuth(authData);
        }

        @Override
        //寻到卡片回调
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            super.onReceiveRfnSearchCard(blnIsSus, cardType, bytCardSn, bytCarATS);
            if (!blnIsSus || cardType == BleNfcDevice.CARD_TYPE_NO_DEFINE) {
                return;
            }
            final int cardTypeTemp = cardType;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean isReadWriteCardSuc;
                    try {
                        if (bleNfcDevice.isAutoSearchCard()) {
                            //如果是自动寻卡的，寻到卡后，先关闭自动寻卡
                            bleNfcDevice.stoptAutoSearchCard();
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);
                            //读卡结束，重新打开自动寻卡
                            startAutoSearchCard();
                        } else {
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);
                            //如果不是自动寻卡，读卡结束,关闭天线
                            bleNfcDevice.closeRf();
                        }
                        //打开蜂鸣器提示读卡完成
                        if (isReadWriteCardSuc) {
                            bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
                        } else {
                            bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
                            Message message = blueHandler.obtainMessage(5);
                            message.obj = getResources().getString(R.string.failed_read_data);
                            message.sendToTarget();
                        }
                    } catch (DeviceNoResponseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public void onReceiveRfmSentApduCmd(byte[] bytApduRtnData) {
            super.onReceiveRfmSentApduCmd(bytApduRtnData);
        }

        @Override
        public void onReceiveRfmClose(boolean blnIsCloseSuc) {
            super.onReceiveRfmClose(blnIsCloseSuc);
        }

        @Override
        //按键返回回调
        public void onReceiveButtonEnter(byte keyValue) {
            if (keyValue == DeviceManager.BUTTON_VALUE_SHORT_ENTER) { //按键短按
                blueHandler.sendEmptyMessage(0);
            } else if (keyValue == DeviceManager.BUTTON_VALUE_LONG_ENTER) { //按键长按
                blueHandler.sendEmptyMessage(0);
            }
        }
    };


    //Scanner 回调
    private ScannerCallback scannerCallback = new ScannerCallback() {
        @Override
        public void onReceiveScanDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
            super.onReceiveScanDevice(device, rssi, scanRecord);
            //搜索蓝牙设备并记录信号强度最强的设备
            if ((scanRecord != null) && (StringTool.byteHexToSting(scanRecord).contains("017f5450"))) {  //从广播数据中过滤掉其它蓝牙设备
                if (rssi < -55) {
                    return;
                }
                blueHandler.sendEmptyMessage(0);
                if (mNearestBle != null) {
                    if (rssi > lastRssi) {
                        mNearestBleLock.lock();
                        try {
                            mNearestBle = device;
                        } finally {
                            mNearestBleLock.unlock();
                        }
                    }
                } else {
                    mNearestBleLock.lock();
                    try {
                        mNearestBle = device;
                    } finally {
                        mNearestBleLock.unlock();
                    }
                    lastRssi = rssi;
                }
            }
        }

        @Override
        public void onScanDeviceStopped() {
            super.onScanDeviceStopped();
        }
    };

    //搜索最近的设备并连接
    private void searchNearestBleDevice() {

        blueHandler.sendEmptyMessage(0);
        if (!mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        mScanner.startScan(0);
                        mNearestBleLock.lock();
                        try {
                            mNearestBle = null;
                        } finally {
                            mNearestBleLock.unlock();
                        }
                        lastRssi = -100;

                        int searchCnt = 0;
                        while ((mNearestBle == null)
                                && (searchCnt < 10000)
                                && (mScanner.isScanning())
                                && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
                            searchCnt++;
                            try {
                                Thread.sleep(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        if (mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mScanner.stopScan();
                            mNearestBleLock.lock();
                            try {
                                if (mNearestBle != null) {
                                    mScanner.stopScan();
                                    Message message = blueHandler.obtainMessage(5);
                                    message.obj = getResources().getString(R.string.connecting_device);
                                    message.sendToTarget();
                                    blueHandler.sendEmptyMessage(0);
                                    bleNfcDevice.requestConnectBleDevice(mNearestBle.getAddress());
                                } else {
                                    Message message = blueHandler.obtainMessage(5);
                                    message.obj = getResources().getString(R.string.device_not_found);
                                    message.sendToTarget();
                                    blueHandler.sendEmptyMessage(0);
                                }
                            } finally {
                                mNearestBleLock.unlock();
                            }
                        } else {
                            mScanner.stopScan();
                        }
                    }
                }
            }).start();
        }
    }

    //开始自动寻卡
    private boolean startAutoSearchCard() throws DeviceNoResponseException {
        //打开自动寻卡，200ms间隔，寻M1/UL卡
        boolean isSuc = false;
        int falseCnt = 0;
        do {
            isSuc = bleNfcDevice.startAutoSearchCard((byte) 20, ComByteManager.ISO14443_P4);
        } while (!isSuc && (falseCnt++ < 10));
        if (!isSuc) {
            //msgBuffer.delete(0, msgBuffer.length());
//			msgBuffer.append("不支持自动寻卡！\r\n");
            blueHandler.sendEmptyMessage(0);
        }
        return isSuc;
    }

    //读写卡Demo
    private boolean readWriteCardDemo(int cardType) {
        switch (cardType) {
            case DeviceManager.CARD_TYPE_ISO4443_B:  //寻到 B cpu卡
                final Iso14443bCard iso14443bCard = (Iso14443bCard) bleNfcDevice.getCard();
                if (iso14443bCard != null) {
//					msgBuffer.append("寻到ISO14443-B卡->UID:(身份证发送0036000008指令获取UID)\r\n");
                    blueHandler.sendEmptyMessage(0);
                    //获取身份证UID的指令流
                    final byte[][] sfzCmdBytes = {
                            {0x00, (byte) 0x84, 0x00, 0x00, 0x08},
                            {0x00, 0x36, 0x00, 0x00, 0x08},
                    };
                    for (byte[] aBytes : sfzCmdBytes) {
                        try {
                            blueHandler.sendEmptyMessage(0);
                            byte returnBytes[] = iso14443bCard.transceive(aBytes);
                            blueHandler.sendEmptyMessage(0);
                        } catch (CardNoResponseException e) {
                            e.printStackTrace();
                            return false;
                        }
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_FELICA:  //寻到FeliCa
                FeliCa feliCa = (FeliCa) bleNfcDevice.getCard();
                if (feliCa != null) {
//					msgBuffer.append("读取服务008b中数据块0000的数据：\r\n");
                    blueHandler.sendEmptyMessage(0);
                    byte[] pServiceList = {(byte) 0x8b, 0x00};
                    byte[] pBlockList = {0x00, 0x00, 0x00};
                    try {
                        byte[] pBlockData = feliCa.read((byte) 1, pServiceList, (byte) 1, pBlockList);
//						msgBuffer.append(StringTool.byteHexToSting(pBlockData)).append("\r\n");
                        blueHandler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ULTRALIGHT: //寻到Ultralight卡
//				String writeText ="ZH-001-CD";
//                if (msgText.getText().toString().length() > 0) {
//                    writeText = msgText.getText().toString();
//                }

                final Ntag21x ntag21x = (Ntag21x) bleNfcDevice.getCard();
                if (ntag21x != null) {
//					msgBuffer.append("寻到Ultralight卡 ->UID:").append(ntag21x.uidToString()).append("\r\n");
                    blueHandler.sendEmptyMessage(0);
                    try {

                        //读写文本Demo，不带进度回调
//						msgBuffer.append("开始写入文本：\r\n");
                        blueHandler.sendEmptyMessage(0);
//						boolean isSuc = ntag21x.NdefTextWrite(writeText);
                        if (true) {
                            Message message = blueHandler.obtainMessage(5);
                            message.obj = getResources().getString(R.string.write_data_successfully);
                            message.sendToTarget();
//								msgBuffer.append("写数据成功！").append("\r\n");
                            blueHandler.sendEmptyMessage(0);
                            Message message2 = blueHandler.obtainMessage(5);
                            message2.obj = getResources().getString(R.string.start_reading_text);
                            message2.sendToTarget();
//								msgBuffer.append("开始读取文本").append("\r\n");
                            blueHandler.sendEmptyMessage(0);
//								String text = ntag21x.NdefTextRead();
                            NdefMessage ndefMessage = ntag21x.NdefRead();
                            if (ndefMessage != null) {
                                NdefRecord[] records = ndefMessage.getRecords();
                                for (NdefRecord record : records) {
//                                    msgBuffer.append("读取成功：\r\n").append(new String(record.getPayload(),"UTF-8")).append("\r\n");
                                    XLog.i("NFC读卡数据：" + new String(record.getPayload(), "UTF-8"));
                                    Message message3 = blueHandler.obtainMessage(6);
                                    message3.obj = new String(record.getPayload(), "UTF-8");
                                    message3.sendToTarget();
                                    blueHandler.sendEmptyMessage(0);
                                }
                            }

                        }
//								msgBuffer.append("读取成功：\r\n").append(text).append("\r\n");
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_MIFARE:   //寻到Mifare卡
                final Mifare mifare = (Mifare) bleNfcDevice.getCard();
                if (mifare != null) {
//					msgBuffer.append("寻到Mifare卡->UID:").append(mifare.uidToString()).append("\r\n");
                    blueHandler.sendEmptyMessage(0);
                    byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
                    try {
                        boolean anth = mifare.authenticate((byte) 0x01, Mifare.MIFARE_KEY_TYPE_A, key);
                        if (anth) {
//							msgBuffer.append("验证密码成功\r\n");
//							msgBuffer.append("写11223344556677889900112233445566到块1\r\n");
                            blueHandler.sendEmptyMessage(0);
                            boolean isSuc = mifare.write((byte) 1, new byte[]{(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, (byte) 0x55, (byte) 0x66,
                                    (byte) 0x77, (byte) 0x88, (byte) 0x99, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, (byte) 0x55, (byte) 0x66});

                            if (isSuc) {
//								msgBuffer.append("写成功！\r\n");
//								msgBuffer.append("读块1数据\r\n");
                                blueHandler.sendEmptyMessage(0);
                                byte[] readDataBytes = mifare.read((byte) 1);
//								msgBuffer.append("块1数据:").append(StringTool.byteHexToSting(readDataBytes)).append("\r\n");
                                blueHandler.sendEmptyMessage(0);
                            } else {
//								msgBuffer.append("写失败！\r\n");
                                blueHandler.sendEmptyMessage(0);
                                return false;
                            }
                        } else {
//							msgBuffer.append("验证密码失败\r\n");
                            blueHandler.sendEmptyMessage(0);
                            return false;
                        }
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ISO15693: //寻到15693卡
                final Iso15693Card iso15693Card = (Iso15693Card) bleNfcDevice.getCard();
                if (iso15693Card != null) {
//					msgBuffer.append("寻到15693卡->UID:").append(iso15693Card.uidToString()).append("\r\n");
//					msgBuffer.append("读块0数据\r\n");
                    blueHandler.sendEmptyMessage(0);
                    try {
                        byte[] cmdBytes = new byte[11];
                        cmdBytes[0] = 0x22;
                        cmdBytes[1] = 0x20;
                        System.arraycopy(iso15693Card.uid, 0, cmdBytes, 2, 8);
                        cmdBytes[10] = 0x01;

//						msgBuffer.append("指令透传发送：" + StringTool.byteHexToSting(cmdBytes) + "\r\n");
                        blueHandler.sendEmptyMessage(0);
                        byte[] returnBytes = iso15693Card.transceive(cmdBytes);
//						msgBuffer.append("返回：" + StringTool.byteHexToSting(returnBytes)).append("\r\n");

                        //读写单个块Demo
//						msgBuffer.append("写数据01020304到块4").append("\r\n");
                        blueHandler.sendEmptyMessage(0);
                        boolean isSuc = iso15693Card.write((byte) 4, new byte[]{0x01, 0x02, 0x03, 0x04});
                        if (isSuc) {
//							msgBuffer.append("写数据成功！").append("\r\n");
                            blueHandler.sendEmptyMessage(0);
                        } else {
//							msgBuffer.append("写数据失败！").append("\r\n");
                            blueHandler.sendEmptyMessage(0);
                        }
//						msgBuffer.append("读块4数据").append("\r\n");
                        blueHandler.sendEmptyMessage(0);
                        byte[] bytes = iso15693Card.read((byte) 4);
//						msgBuffer.append("块4数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
                        blueHandler.sendEmptyMessage(0);

                        //读写多个块Demo
//						msgBuffer.append("写数据0102030405060708到块5、6").append("\r\n");
                        blueHandler.sendEmptyMessage(0);
                        isSuc = iso15693Card.writeMultiple((byte) 5, (byte) 2, new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
                        if (isSuc) {
//							msgBuffer.append("写数据成功！").append("\r\n");
                            blueHandler.sendEmptyMessage(0);
                        } else {
//							msgBuffer.append("写数据失败！").append("\r\n");
                            blueHandler.sendEmptyMessage(0);
                        }
//						msgBuffer.append("读块5、6数据").append("\r\n");
                        blueHandler.sendEmptyMessage(0);
                        bytes = iso15693Card.ReadMultiple((byte) 5, (byte) 2);
//						msgBuffer.append("块5、6数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
                        blueHandler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
        }
        return true;
    }


    @SuppressLint("HandlerLeak")
    private Handler blueHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                /*获取设备版本号*/
                                byte versions = bleNfcDevice.getDeviceVersions();
                                blueHandler.sendEmptyMessage(0);

                                /*获取设备电池电压*/
                                double voltage = bleNfcDevice.getDeviceBatteryVoltage();
                                blueHandler.sendEmptyMessage(0);

                                /*设置快速传输参数*/
                                bleNfcDevice.androidFastParams(true);
                                blueHandler.sendEmptyMessage(0);

                                blueHandler.sendEmptyMessage(0);
                                byte[] newSerialNumberBytes = new byte[]{
                                        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0xee, (byte) 0xff,
                                        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0xee, (byte) 0xff
                                };
//								isSuc = bleNfcDevice.changeSerialNumber(newSerialNumberBytes);
//								if (isSuc) {
//									msgBuffer.append("\r\n设备序列号修改成功!");
//								}
//								else {
////									msgBuffer.append("\r\n设备序列号修改失败!");
//								}
                                blueHandler.sendEmptyMessage(0);

                                /*获取设备序列号*/
//								try {
//									msgBuffer.append("\r\n开始获取设备序列号...\r\n");
//									blueHandler.sendEmptyMessage(0);
//									byte[] serialNumberBytes = bleNfcDevice.getSerialNumber();
//									msgBuffer.append("设备序列号为：").append(StringTool.byteHexToSting(serialNumberBytes));
//								}catch (DeviceNoResponseException e) {
//									e.printStackTrace();
//								}
//
//								/*开启自动寻卡*/
//								msgBuffer.append("\n开启自动寻卡...\r\n");
                                blueHandler.sendEmptyMessage(0);
                                //开始自动寻卡
                                startAutoSearchCard();
                            } catch (DeviceNoResponseException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                case 5:
                    String obj = (String) msg.obj;
                    if (bluetoothDialog.isShowing()) {
                        bluetoothDialog.setMessageText(obj);
                    }
                    break;
                case 6:
                    String obj2 = (String) msg.obj;
                    if (bluetoothDialog.isShowing()) {
                        bluetoothDialog.setMessageText(getResources().getString(R.string.read_success) + obj2);
                    }
                    Intent intent = new Intent();
                    intent.putExtra(SCAN_RESULT, obj2);
                    //是否在手动选择设备界面进行了扫码
                    intent.putExtra("isscan", false);
                    setResult(RESULT_OK, intent);
                    bluetoothDialog.dismiss();
                    finish();

                    break;
            }
        }
    };


}
